import SockJS from 'sockjs-client';
import { Client } from '@stomp/stompjs';

let stompClient = null;
let isConnected = false;

// 存储回调函数
const mqttDataCallbacks = new Set();

export function connectWebSocket() {
  const socket = new SockJS('http://localhost:8080/ws');
  
  stompClient = new Client({
    webSocketFactory: () => socket,
    //debug: (str) => console.log('[WebSocket]', str),
    onConnect: () => {
        isConnected = true;
        console.log('✅ WebSocket 连接成功');
        // 订阅MQTT数据通道
        stompClient.subscribe('/topic/mqttData', (message) => {
        const data = JSON.parse(message.body);
        console.log('📡 收到MQTT数据:', data);  
        // 执行所有回调函数
        mqttDataCallbacks.forEach(cb => cb(data));
        });
        // 订阅MQTT数据通道
        stompClient.subscribe('/topic/mqttPressureData', (message) => {
        const data = JSON.parse(message.body);
        console.log('📡 收到 MQTT 压力数据:', data);
        // 执行所有回调函数
        mqttDataCallbacks.forEach(cb => cb(data));
        });
    },
    onStompError: (error) => {
      console.error('❌ WebSocket连接错误:', error);
      isConnected = false;
    }
  });

  stompClient.activate();
}

// 注册MQTT数据回调
export function onMqttData(callback) {
  mqttDataCallbacks.add(callback);
  return () => mqttDataCallbacks.delete(callback);
}

export function disconnectWebSocket() {
  if (stompClient !== null) {
    stompClient.disconnect()
    isConnected = false
    console.log('WebSocket已断开')
  }
}

export function sendTestMessage() {
  if (isConnected && stompClient) {
    // 发送消息到后端
    stompClient.send('/app/test', {}, JSON.stringify({}))
    console.log('已发送测试消息到后端')
  } else {
    console.warn('WebSocket未连接，无法发送消息')
  }
}

export function checkConnection() {
  return isConnected
}